<?php

namespace common\components\helpers;
use yii\base\BaseObject;
use yii\helpers\ArrayHelper;

/**
 * 数组树形数据操作助手类
 * @author: 郭建飞
 * Date: 2015-3-11
 * Time: 11:11
 */
class Tree extends BaseObject{

    /**
     * @var array $arr 生成树所需要的原始数组
     */
    public $arr;

	/**
	* @var array $icon 生成树型结构所需修饰符号，可以换成图片
	*/
	public $icon;

    /**
     * @var string $nbsp 生成树形结构所需要的空格字符
     */
	public $nbsp;


	public $tt_parent_id;

	public function __construct($arr,$icon=['│','├','└'],$nbsp='&nbsp;'){
        $this->arr=$arr;
        $this->icon=$icon;
        $this->nbsp=$nbsp;
    }

    /**
     * 得到父级数组
     * @param int
     * @return array
     */
    public function get_parent($myid){
        $newarr = array();
        if(!isset($this->arr[$myid])) return false;
        $pid = $this->arr[$myid]['parent_id'];
        $pid = $this->arr[$pid]['parent_id'];
        if(is_array($this->arr)){
            foreach($this->arr as $id => $a){
                if($a['parent_id'] == $pid) $newarr[$id] = $a;
            }
        }
        return $newarr;
    }

    /**
     * 得到子级数组
     * @param int
     * @return array
     */
    public function get_child($myid){
        $a = $newarr = array();
        if(is_array($this->arr)){
            foreach($this->arr as $id => $a){
                if($a['parent_id'] == $myid) $newarr[$id] = $a;
            }
        }
        return $newarr ? $newarr : false;
    }


    /**
     * 得到当前位置数组
     * @param int
     * @return array
     */
    public function get_pos($myid,&$newarr){
        $a = array();
        if(!isset($this->arr[$myid])) return false;
        $newarr[] = $this->arr[$myid];
        $pid = $this->arr[$myid]['parent_id'];
        if(isset($this->arr[$pid])){
            $this->get_pos($pid,$newarr);
        }
        if(is_array($newarr)){
            krsort($newarr);
            foreach($newarr as $v){
                $a[$v['id']] = $v;
            }
        }
        return $a;
    }

    /**
     * 得到当前数组等级
     * @param int
     * @return array
     */
    public function get_level($myid,$level=1){
        if(!isset($this->arr[$myid])) return 0;
        $pid = $this->arr[$myid]['parent_id'];
        if(isset($this->arr[$pid])){
            $level++;
            $this->get_level($pid,$level);
        }
        return $level;
    }


    public function get_tree_array($mid=0,$level=0){
        $tree=[];
        foreach($this->arr as $m){
            if($m['parent_id']==$mid){//若是子级
                $m['level']=$level+1;
                $m['children']=$this->get_tree_array($m['id'],$level+1);
                $tree[]=$m;
            }
        }
        return $tree;
    }
    public function get_tree_app_array($mid=0,$level=0){
        $tree=[];
        $arr = [];
        foreach($this->arr as $m){
            if($m['parent_id']==$mid){//若是子级
                $arr['level']=$level+1;
                $arr['name']=$m['name'];
                $arr['id']=$m['id'];
                $arr['children']=$this->get_tree_app_array($m['id'],$level+1);
                $tree[]=$arr;
            }
        }
        return $tree;
    }



    public function get_jquery_tree_array($mid=0,$level=0){
        $tree=[];
        $flag=false;
        foreach($this->arr as $m){
            if($m['parent_id']==$mid){
                $flag=true;break;
            }
        }
        if($flag){
            foreach($this->arr as $m){
                if($m['parent_id']==$mid){//若是子级
                    if($mid!=0){
                        $array=explode('-', $this->tt_parent_id);
                        if(!(in_array($mid,$array))){
                            $this->tt_parent_id.=empty($this->tt_parent_id)?$mid:'-'.$mid;
                        }
                    }else{
                        $this->tt_parent_id='';
                    }
                    $m['tt-parent-id']=$this->tt_parent_id;
                    $m['level']=$level+1;
                    $m['children']=$this->get_jquery_tree_array($m['id'],$level+1);
                    $tree[]=$m;
                }
            }
        }else{
            $old_array=explode('-', $this->tt_parent_id);
            array_pop($old_array);
            $this->tt_parent_id=implode('-',$old_array);
        }

        return $tree;
    }

    public function get_tt_parent($myid){
        $newarr ='';
        if(!isset($this->arr[$myid])) return false;
        $pid = $this->arr[$myid]['parent_id'];
        foreach($this->arr as $id => $a){
            if($a['id'] == $pid) {
                $newarr=empty($newarr)?$a['id']:'-'.$a['id'];
                $this->get_tt_parent($a['id']);
            }
        }
        return $newarr;
    }

    public function getTreeTable($myId, $template='', $selectId = 0)
    {
        if (!is_array($this->arr))return '';
        $menuArray=$this->arr;
        $returnStr='';
        $treeTable = function ($myId, $template, $selectId, $adds = '') use (&$treeTable, &$returnStr,&$menuArray) {
            $number = 1;
            $childArray = [];
            $callback = function ($menu, $id) use (&$childArray, $myId) {
                if ($menu['parent_id'] == $myId) $childArray[$id] = $menu;
            };
            array_walk($menuArray, $callback);
            if (is_array($childArray)) {
                $total = count($childArray);
                foreach ($childArray as $id => $value) {
                    $j = $k = '';
                    if ($number == $total) {
                        $j .= $this->icon[2];
                    } else {
                        $j .= $this->icon[1];
                        $k = $adds ? $this->icon[0] : '';
                    }
                    $spacer = $adds ? $adds . $j : '';
                    $selected = $id == $selectId ? 'selected' : '';
                    @extract($value);
                    eval("\$nstr = \"$template\";");
                    $returnStr .= $nstr;
                    unset($menuArray[$id]);
                    $treeTable($id, $template, $selectId, $adds . $k . $this->nbsp);
                    $number++;
                }
            }
        };
        $treeTable($myId, $template, $selectId);
        return $returnStr;

    }

    public function get_tree_select($mid=0,$adds = '',$tree=[]){
        $number=1;
        $child = $this->get_child($mid);//得到所有的子集数组
        if(is_array($child)){
            $total = count($child);
            foreach($child as $id=>$a){
                $j=$k='';
                if($number==$total){
                    $j .= $this->icon[2];//└
                }else{
                    $j .= $this->icon[1];//├
                    $k = $adds ? $this->icon[0] : '';//│
                }
                $spacer = $adds ? $adds.$j : '';
                $tree[$id]=$spacer.$a['name'];
                $tree=$this->get_tree_select($id, $adds.$k.$this->nbsp,$tree);
                $number++;
            }
        }
        return $tree;
    }
    public function get_tree_sleect_app_array($mid=0,$level=0){
        static  $arrTree;
        $level++;
        $vals = [];
        $child = $this->get_child($mid);//得到所有的子集数组
        if(is_array($child)) {
            foreach ($child as $val) {
                $vals['level'] = $level;
                $vals['name'] = $val->name;
                $vals['parent_id'] = $val->parent_id;
                $vals['id'] = $val->id;
                $arrTree[$vals['id']] = $vals;
                $this->get_tree_sleect_app_array($val->id, $level);
            }
        }
        return $arrTree;
    }

	public function get_tree($myid, $str, $ret = '', $sid = 0, $adds = '', $str_group = '')
    {
        $number = 1;
        $child = $this->get_child($myid);
        if (is_array($child)) {
            $total = count($child);
            foreach ($child as $id => $value) {
                $j = $k = '';
                if ($number == $total) {
                    $j .= $this->icon[2];
                } else {
                    $j .= $this->icon[1];
                    $k = $adds ? $this->icon[0] : '';
                }
                $spacer = $adds ? $adds . $j : '';
                $selected = $id == $sid ? 'selected' : '';
                @extract($value);
                $parent_id == 0 && $str_group ? eval("\$nstr = \"$str_group\";") : eval("\$nstr = \"$str\";");
                $ret .= $nstr;
                $nbsp = $this->nbsp;
                $ret=$this->get_tree($id, $str, $ret, $sid, $adds . $k . $this->nbsp, $str_group);
                $number++;
            }
        }
        return $ret;
    }

}
?>